package me.helllp.book.netty.step06;

import java.util.Date;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

public class EchoServerHandler extends ChannelInboundHandlerAdapter{
	
	private int iCount;
	
	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
//		ByteBuf buf = (ByteBuf)msg;
//		byte[] req = new byte[buf.readableBytes()];
//		buf.readBytes(req);
//		
//		System.out.println("收到消息：" + new String(req,"UTF-8"));
//		ctx.write(msg);
		String body = (String)msg;
		
		System.out.println("时间服务器收到的消息：" + body + ";这是第几次发送：" +  ++iCount);
		
		String currentTime = "TIME".equalsIgnoreCase(body) ? new Date(System.currentTimeMillis()).toString() : "未响应的命令";
//		currentTime = currentTime + System.lineSeparator();
		currentTime = "$_" + currentTime;
		
		ByteBuf buf = Unpooled.copiedBuffer(currentTime.getBytes());
		ctx.writeAndFlush(buf);
	}
	
	@Override
	public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
		ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
	}
	
	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		cause.printStackTrace();
		ctx.close();
	}
}
